#拼多多物流信息



import requests,json,time
from common.config import *
from common.Helper import Helper

class Logistics( object ):

    def __init__(self):

        pass

    def requestIndex(self,task=None):

        resp = {'type': 102, 'msg': '物流任务','content':{}}

        # 设置cookie
        header['cookie'] = task['cookie']

        r = requests.get( url = domain_url['logistics_url'].format(str( task['order_sn'])),headers=header)

        if r.status_code == 200 and not r.json()['success']:

            if '订单未发货' in r.json()['error_msg']:

                global  items

                items = None

            else:
                # 订单未发货以及异常情况处理
                error = dict( errorCode=r.json()['error_code'],errorMsg=r.json()['error_msg'])
                resp['content']['content'] = task
                resp['content']['errcode'] = error['errorCode']
                resp['content']['errmsg'] = error['errorMsg']
                resp['content']['data'] = {}

                content = Helper.changeBase64(json.dumps(resp['content']))

                resp['content'] = content.decode('ascii')

                print(error)

                return resp


        items = r.json()['result']

        order_sn = task['order_sn']

        data = self.parseJson(items,order_sn)

        resp['content']['content'] = task
        resp['content']['data'] = (data)
        resp['content']['errcode'] = 0
        resp['content']['errmsg'] = '任务完成'

        print( resp )

        content = Helper.changeBase64(json.dumps(resp['content']))

        resp['content'] = content.decode('ascii')

        return resp

    def parseJson(self,items,order_sn):

        data = {'orders_sn':order_sn,'delivery_company':None,'shipping_status':None}

        if not items:
            #订单未发货
            data['shipping_status'] = 1

            return ( data )

        else:
            # 已发货代签收
            if 'SIGN' not in json.dumps(items):

                data['delivery_company'] = items['shipping_name']
                data['shipping_status'] = 2

                return ( data )

            else:

                data['delivery_company'] = items['shipping_name']
                data['shipping_status'] = 3

                return  (data)



if __name__ == '__main__':

    l = Logistics()

    task = {
        "type": 204,
        "content": {
            "task_order_id": 26,
            "owner_id": 186716817,
            "order_sn": "190628-147189924550721",
            "cookie": "_nano_fp=Xpdjl0UyXpEqn5Tjn9_hcqX3_GdIDNGobRfgDlMO;_nano_fp=Xpdjl0UyXpEqn5Tjn9_hcqX3_GdIDNGobRfgDlMO;PASS_ID=1-A2WKIav5GBsz0Jp8QV6+GP5ff+Sw2kjokhgReoom02NzvMmPD/7ZQL4zxnQq4HDoUpHKB7I9J/VtNHDlNsp5YQ_186716817_29159208"
        },

        "msg": "物流任务"
    }

    task = task['content']

    l.requestIndex(task)